package com.yanqu.road.entity.activity.suitang.entity.rank;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;

public class CrossSuiTangSpecialRankListModel {

    private Comparator<CrossSuiTangSpecialRank> rankSort = new CrossSuiTangSpecialRankSort();

    private LinkedList<CrossSuiTangSpecialRank> rankList = new LinkedList<>();

    public void rankChange(CrossSuiTangSpecialRank rank) {
        synchronized (this) {

            boolean change = false;

            boolean find = false;
            for (CrossSuiTangSpecialRank tmpRank : rankList) {
                // 找到了
                if (Objects.equals(tmpRank.getUserId(), rank.getUserId())) {
                    tmpRank.setValue(rank.getValue());
                    tmpRank.setTime(rank.getTime());
                    change = true;
                    find = true;
                    break;
                }
            }

            if (!find) {
                rankList.add(rank);
                change = true;
            }

            if (change) {
                rankSort();
            }

        }
    }

    public CrossSuiTangSpecialRank getMyRankInfo(long userId) {
        CrossSuiTangSpecialRank rank = null;
        synchronized (this) {
            for (CrossSuiTangSpecialRank userRank : rankList) {
                if (userRank.getUserId() == userId) {
                    rank = userRank;
                    break;
                }
            }
        }
        return rank;
    }

    public int getMyRank(long userId) {
        int rank = -1;
        int index = 0;
        synchronized (this) {
            for (CrossSuiTangSpecialRank userRank : rankList) {
                if (userRank.getUserId() == userId) {
                    rank = index + 1;
                    break;
                }
                index++;
            }
        }
        return rank;
    }

    public LinkedList<CrossSuiTangSpecialRank> getRankList() {
        return new LinkedList<>(rankList);
    }

    public void setRankList(LinkedList<CrossSuiTangSpecialRank> rankList) {
        synchronized (this) {
            this.rankList = rankList;
            rankSort();
        }
    }

    /**
     * 排序，记得加锁
     */
    private void rankSort() {
        rankList.sort(rankSort);
    }
}
